const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

async function initDatabase() {
    let connection;
    
    try {
        console.log('🔄 正在连接数据库...');
        
        // 创建数据库连接
        connection = await mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'newhand',
            multipleStatements: true
        });
        
        console.log('✅ 数据库连接成功');
        
        // 创建数据库（如果不存在）
        await connection.execute('CREATE DATABASE IF NOT EXISTS hunaction CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
        await connection.execute('USE hunaction');
        
        console.log('✅ 数据库选择成功');
        
        // 读取SQL文件
        const sqlFilePath = path.join(__dirname, '..', 'create_tables.sql');
        const sqlContent = fs.readFileSync(sqlFilePath, 'utf8');
        
        console.log('🔄 正在执行SQL脚本...');
        
        // 分割SQL语句（按分号分割，忽略注释行）
        const sqlStatements = sqlContent
            .split(';')
            .map(stmt => stmt.trim())
            .filter(stmt => stmt.length > 0 && !stmt.startsWith('--') && !stmt.startsWith('/*'));
        
        for (const statement of sqlStatements) {
            if (statement.trim()) {
                try {
                    await connection.execute(statement);
                } catch (error) {
                    if (!error.message.includes('already exists') && !error.message.includes('Table') && !error.message.includes('exists')) {
                        console.warn('⚠️ SQL执行警告:', error.message);
                    }
                }
            }
        }
        
        console.log('✅ 数据库表创建完成！');
        
        // 验证表是否创建成功
        const [tables] = await connection.execute('SHOW TABLES');
        console.log('📋 已创建的表:');
        tables.forEach(table => {
            console.log(`  - ${Object.values(table)[0]}`);
        });
        
    } catch (error) {
        console.error('❌ 数据库初始化失败:', error.message);
        process.exit(1);
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    initDatabase();
}

module.exports = initDatabase; 